<?php
//浏览器为我开放一块空间用于存放我的登录信息
session_start();

//isset（）用于检测变量$session["user"]是否存在
//判断用户是否登录
// ' ? :'三目运算符： '？'前面为判断条件， '：'前后为表达式
//判断结果为true就执行：前面表达式，判断结果为false则执行：后面表达式
$currentUser = isset($_SESSION["user"])?$_SESSION["user"]:null;
//header("")这里用作页面跳转
//若用户未登录，则跳转至登录页面并退出当前脚本
if(!$currentUser){
    header("Location: login.php");
    die(0);
}

//页面容量(最多可以显示八组数据)
$pageSize = 8;

/*
$theme = isset($_GET["theme"])?$_GET["theme"]:null;
if(!$theme){
    $theme = $_COOKIE["theme"];
}else{
    setcookie("theme",$theme);
}
if(!$theme) $theme = "default"; 
*/

//当前页面
$pageIndex = isset($_GET["pageIndex"])?$_GET["pageIndex"]:null;
//当前页面不能为负，否则跳转到页面1
if($pageIndex<=0) $pageIndex = 1;


 /************查询条件部分*************/
 
//检测title author minTime maxTime这些数据是否读出
$queryTitle = isset($_GET["title"])?$_GET["title"]:null;
$queryAuthor = isset($_GET["author"])?$_GET["author"]:null;
$queryMinTime = isset($_GET["minTime"])?$_GET["minTime"]:null;
$queryMaxTime = isset($_GET["maxTime"])?$_GET["maxTime"]:null;
//查询条件
// %% 表示模糊查找，只要与$queryTitl有相同的字符就会被查询出来，
//例如$queryTitl="光爸爸",那么所有含有'光''爸'字符的字段就会被查询出来
$where = "";
if($queryTitle) {
    $where = " `Title` like ('%$queryTitle%')";
}
// .= 在这里起到了连接上面$queryTitle中的$where
//最后表示为sql与语句:where title like '%$queryTitle%' and where AuthorName like '%$queryAuthor%'
if($queryAuthor){
    if($where) $where .= " AND `AuthorName` like ('%$queryAuthor%')"; 
    else $where .= "`AuthorName` like ('%$queryAuthor%')";   
}
if($queryMinTime){
    if($where) $where .= " AND "; 
    $where .= "createTime>='$queryMinTime'";   
}
if($queryMaxTime){
    if($where) $where .= " AND "; 
    $where .= "createTime<='$queryMaxTime'";   
}
//将sql中的where变成变量以达到多种查询的效果
if($where) $where = "WHERE $where";

//每一页最上面的数据
$startRow = ($pageIndex -1)*$pageSize;


/***************MYSQL部分************/

//sql查询语句
$sql = "select * from `article` $where order by `createTime` desc limit $startRow,$pageSize ";
//连接数据库 new mysqli()
$conn = new mysqli("localhost","root","","myblog");
//query()执行sql语句，成功返回true，失败返回false
//执行$sql语句并返回返回一个资源标识符
$rs = $conn->query($sql);
//判断数据库是否连接成功 失败则退出当前脚本
if($conn->error) die($conn->error);
//定义数组变量rows
$rows=[];
//fetch_assoc（）从$rs获取一行数据作为关联数组
//用while循环将获取的关联数组写入$rows中
while($row = $rs->fetch_assoc()){
    $rows[]=$row;
}
//关闭$rs的MYSQL连接
$rs->close();

//统计文章数目
$totalSql = "select count(Id) as total from `article` $where";
//执行$totalSql语句并返回一个资源标识符：object(mysqli_result)#2 (5) { ["current_field"]=> int(0) ["field_count"]=> int(1) ["lengths"]=> array(1) { [0]=> int(2) } ["num_rows"]=> int(1) ["type"]=> int(0) }
$rs = $conn->query($totalSql);
//取出数组元素: $rs = count(Id)
$total = $rs->fetch_assoc()['total'];

//ceil()函数 向上取整 例如：ceil(0.001)的结果为1
//求页码数量
$pageCount = ceil($total/$pageSize);


/***********翻页**********/
         
//$_GET函数
function makePageUrl($pageIndex){
    $url = "article_list.php?";
    //$_GET  获取网页上面的页数例如：pageIndex=1或者pageIndex=1&pageIndex（浏览器地址栏）
    foreach($_GET as $k =>$v){
        //$k的值为pageIndex或者&pageIndex
        if($k==="pageIndex"){
            continue;
        }
        $url .=$k."=".$v."&";//article_list.php?&pageIndex=$pageIndex&
    }
    $url .="pageIndex=".$pageIndex;//article_list.php?&pageIndex=$pageIndex&pageIndex=$pageIndex
    return $url;
}

?>

<!DOCtype html>
<html>
    <head>
        <title>myBlog</title>
        <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        <link type="text/css" rel="stylesheet" href="article_list.css">
    </head>
    <body>
        <div class="container">
            <div class="col-5" id="header">
                <p class="col-4">我 的 博 客</p>
                <a href="logout.php">退出</a>
                <div class="col-1">当前用户:  <?=$currentUser["Username"]?></div>
            </div>
            <div class="col-5" id="menu"><!--导航栏start-->
                <div class="col-6" id="menu-1">
                    <ul class="col-6"><!--一级菜单-->
                        <li class="col-1">
                            <a href="article_list.php?<?=makePageUrl(1)?>">首页</a>
                            <ul class="col-6"><!--二级菜单-->
                                <li class="col-6">查看文章</li>
                                <li class="col-6"><a href="article_add.php">添加文章</a></li>
                                <li class="col-6">热门文章</li>
                            </ul>
                        </li>
                        <li class="col-1">
                            <a href="#">网站链接</a>
                            <ul class="col-6"><!--二级菜单-->
                                <li class="col-6"><a href="https://www.bilibili.com">B站</a></li>
                                <li class="col-6"><a href="https://www.baidu.com/">百度</a></li>
                                <li class="col-6"><a href="https://www.taobao.com">淘宝</a></li>
                            </ul>
                        </li>
                        <!--二级菜单-->
                        <li class="col-1">正在搭建...</li>
                        <li class="col-1">正在搭建...</li>
                        <li class="col-1">正在搭建...</li>
                    </ul>
                </div>
            </div><!--导航栏end--> 
            <div class="col-5" id="main">
                <div class="col-5" id="searchFor"><!--搜索栏start-->
                    <form action="article_list.php" method="get">
                    <span>
                        <label>标题</label>
                        <input type="text" value="<?=$queryTitle ?>" name="title" />
                    </span>
                    <span>
                        <label>作者</label>
                        <input type="text" value="<?=$queryAuthor ?>" name="author" />
                    </span>
                    <span>
                        <label>时间范围：</label>
                        从 <input type="text" value="<?=$queryMinTime ?>" name="minTime" />
                        到 <input type="text" value="<?=$queryMaxTime?>" name="maxTime" />
                    </span>
                    <input type="submit" value="搜索" id="btn" />
                    </form>
                </div><!--搜索栏end-->
                <div  class="col-5" id="tableTitle">
                    <p>文章列表</p>
                </div>
                <span id="listBtn" class = "btn">列表</span><!--切换样式-->
                <span id="cardBtn" class = "btn">卡片</span>
                <div id="listpanel" class = "list">
                    <div class="col-5" id="table"><!--显示栏start-->
                        <div class="col-6" id="thead">
                            <div class="col-6" id="tr">
                                <div class="col-1" id="td">标题</div>
                                <div class="col-1" id="td">作者</div>
                                <div class="col-1" id="td">时间</div>
                                <div class="col-1" id="td">操作</div>
                            </div>
                        </div>
                        <div class="col-6" id="tbody">
                            <?php if($rows) { ?>    
                            <?php foreach($rows as $row){ ?>
                                <div class="col-1" id="tr">
                                    <div class="col-6" id="td">
                                        <a href="article_detail.php?Id=<?=$row["Id"]?>" title="<?=$row["Title"]?>"><?=$row["Title"]?></a>
                                    </div>
                                    <div class="col-6" id="td">
                                        <?=$row["AuthorName"]?>
                                    </div>
                                    <div class="col-6" id="td">
                                        创建时间：<?=$row["CreateTime"]?></br>
                                        修改时间：<?=$row["UpdateTime"]?>
                                    </div>
                                    <div class="col-6" id="td">
                                        <a href="article_detail.php?Id=<?=$row["Id"]?>">详情</a>
                                        <?php if($currentUser["Username"]===$row["AuthorName"]) {?>
                                        <a href="article_modify.php?Id=<?=$row["Id"]?>"> 修改 </a>
                                        <a href="#">删除</a>
                                        <?php }?>
                                    </div>
                                </div>    
                                <?php } ?>
                                <?php }else { ?>
                                    <div id="noData">没有数据....</div>
                            <?php }?>
                        </div>   
                    </div><!--显示栏end-->
                </div>
                <div class="col-5" id="page"><!--翻页start-->
                    共<?=$total?>条记录，共<?=$pageCount?>页   当前第<?=$pageIndex?>页  
                    <a href="article_list.php?<?=makePageUrl(1)?>">首页</a><
                    <?php for($i=1;$i<=$pageCount;$i++) { ?>
                        <a class="<?=$pageIndex==$i?'currentPageNo':''?>"  href="article_list.php?<?=makePageUrl($i)?>"><?=$i?></a>
                    <?php }?>
                    >
                    <a href="article_list.php?<?=makePageUrl($pageCount)?>">尾页</a>           
                </div>
            </div><!--翻页end-->
            <div class="col-5" id="footer">
                <div col-4>
                    <a href="https://www.bilibili.com/video/BV1NZ4y1j7nw?p=2"><span>黑人抬棺</span></a>
                    <span>专业团队</span>
                    <span>诚信可靠</span>
                    <span>联系电话</span>
                    <span>8-8-8-8-8-8-8-8</span>
                </div>
            </div>
        </div>
        <script type="text/javascript">
            var listBtn = document.getElementById("listBtn").onclick = function(){
                document.getElementById("listpanel").className="list";
            };
            var cardBtn = document.getElementById("cardBtn").onclick = function(){
                document.getElementById("listpanel").className="card";
            };

            var menu1 = document.getElementById("menu-1");
            var fMenu = menu1.firstElementChild;
            var lis = fMenu.getElementsByTagName("li");

            for(i = 0,j = lis.length;i<=j;i++){
                (function(li){
                    li.onmouseenter = function(){
                    var enterLi = li;
                    var ul = enterLi.children[1];
                    if(!ul) return;
                    ul.style.opacity = 0.5;

                    let tick = setInterval(function(){
                        var opacity = parseFloat(ul.style.opacity);
                        opacity += 0.05;
                        if(opacity>=0.8){
                            ul.style.opacity = 0.8;
                            clearInterval(tick);
                            ul.tick = 0;
                        }else{
                            ul.style.opacity = opacity;
                        }
                    },100);
                    ul.tick = tick;
                };
                })(lis[i]);
            }
        </script>
    </body>
</html>